<?php
declare(strict_types=1);

namespace think\admin\test\repository;

use think\admin\Repository;
use think\admin\test\model\User;
use think\admin\exception\DataException;

class UserRepository extends Repository
{
    /**
     * 初始化
     */
    protected function initialize(): void
    {
        $this->model = new User();
    }

    /**
     * 根据用户名获取用户
     * @param string $username
     * @return User
     * @throws DataException
     */
    public function findByUsername(string $username): User
    {
        $user = $this->model->where('username', $username)->find();
        if (!$user) {
            throw new DataException('用户不存在');
        }
        return $user;
    }

    /**
     * 检查用户名是否存在
     * @param string $username
     * @param int|null $excludeId 排除的用户ID
     * @return bool
     */
    public function isUsernameExists(string $username, ?int $excludeId = null): bool
    {
        $query = $this->model->where('username', $username);
        if ($excludeId) {
            $query->where('id', '<>', $excludeId);
        }
        return (bool)$query->count();
    }

    /**
     * 检查邮箱是否存在
     * @param string $email
     * @param int|null $excludeId 排除的用户ID
     * @return bool
     */
    public function isEmailExists(string $email, ?int $excludeId = null): bool
    {
        $query = $this->model->where('email', $email);
        if ($excludeId) {
            $query->where('id', '<>', $excludeId);
        }
        return (bool)$query->count();
    }

    /**
     * 获取用户角色
     * @param int $userId
     * @return array
     */
    public function getUserRoles(int $userId): array
    {
        $user = $this->model->with('roles')->find($userId);
        return $user ? $user->roles->toArray() : [];
    }

    /**
     * 分配角色
     * @param int $userId
     * @param array $roleIds
     * @return bool
     * @throws DbException
     */
    public function assignRoles(int $userId, array $roleIds): bool
    {
        return $this->transaction(function() use ($userId, $roleIds) {
            $user = $this->model->find($userId);
            if (!$user) {
                return false;
            }

            // 删除原有角色
            $user->roles()->detach();

            // 分配新角色
            return (bool)$user->roles()->attach($roleIds);
        });
    }

    /**
     * 批量分配角色
     * @param array $userIds
     * @param array $roleIds
     * @return bool
     * @throws DbException
     */
    public function batchAssignRoles(array $userIds, array $roleIds): bool
    {
        return $this->transaction(function() use ($userIds, $roleIds) {
            $users = $this->model->whereIn('id', $userIds)->select();
            if ($users->isEmpty()) {
                return false;
            }

            foreach ($users as $user) {
                // 删除原有角色
                $user->roles()->detach();
                // 分配新角色
                if (!$user->roles()->attach($roleIds)) {
                    return false;
                }
            }

            return true;
        });
    }

    /**
     * 移除用户角色
     * @param int $userId
     * @param array $roleIds
     * @return bool
     */
    public function removeRoles(int $userId, array $roleIds): bool
    {
        $user = $this->model->find($userId);
        if (!$user) {
            return false;
        }
        return (bool)$user->roles()->detach($roleIds);
    }

    /**
     * 更新用户状态
     * @param int $userId
     * @param int $status
     * @return bool
     */
    public function updateStatus(int $userId, int $status): bool
    {
        return (bool)$this->model->where('id', $userId)->update(['status' => $status]);
    }

    /**
     * 批量更新用户状态
     * @param array $userIds
     * @param int $status
     * @return bool
     */
    public function batchUpdateStatus(array $userIds, int $status): bool
    {
        return (bool)$this->model->whereIn('id', $userIds)->update(['status' => $status]);
    }
} 